package cn.com.cifi.mars.web.action.report;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.vo.PageResult;
import cn.com.cifi.mars.bean.vo.signPlan.SignPlanProgressVo;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.*;
import cn.com.cifi.mars.entity.SignPlanProgress;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.SignPlanProgressService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.SignPlanProgressTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * 签约计划进度表
 * @author: jyx
 * @date: 2020/7/27 9:26
 */
@Slf4j
@RestController
public class SignPlanProgressController extends BaseAction implements ISignPlanProgressController {

    @Autowired
    private SignPlanProgressService signPlanProgressService;
    @Autowired
    private IdmUserService idmUserService;
    @Autowired
    private SysLogService sysLogService;

    /**
     * 刷新签约计划进度底表
     * @param apiVersion
     * @param yearMonth
     * @return
     */
    @Override
    public R refreshSignPlanProgress(String apiVersion, String yearMonth) {
        signPlanProgressService.refresh(yearMonth);
        return ok("刷新成功");
    }

    /**
     * 获取签约进度表数据
     * @param apiVersion
     * @param yearMonth 指定年月
     * @param name 模糊搜索字段(区域名称、城市名称、项目名称)
     * @param versionStatus 版本状态
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public R signPlanProgress(String apiVersion, String yearMonth, String name, String versionStatus, String startTime, String endTime) {
        saveLog(LogEventEnum.BROWSE,"签约计划进度表","签约计划进度表",startTime + ":" + endTime);
        //查询用户权限项目id列表
        List<String> projectIdList = prepareUserDataPermission(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }
        List<SignPlanProgressVo> list =  signPlanProgressService.getSignPlanProgressVo(yearMonth,projectIdList,name,versionStatus,startTime,endTime);
        return ok(list);
    }


    /**
     * 获取签约进度表分页数据
     * @param apiVersion
     * @param current 页码
     * @param pageSize 条数
     * @param yearMonth 指定年月
     * @param name 模糊搜索字段(区域名称、城市名称、项目名称)
     * @param versionStatus 版本状态
     * @param startTime 起始时间
     * @param endTime 结束时间
     * @return
     */
    @Override
    public R signPlanProgressPage(String apiVersion, String current, String pageSize, String yearMonth, String name, String versionStatus, String startTime, String endTime) {
        List<String> projectIdList = prepareUserDataPermission(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }
        //分页条件查询
        PageResult page =  signPlanProgressService.getSignPlanProgressPage(current,pageSize,yearMonth,projectIdList,name,versionStatus,startTime,endTime);
        return ok(page);
    }


    /**
     * 签约进度表导出
     * @param apiVersion
     * @param response
     * @param yearMonth
     */
    @Override
    public void signPlanProgressExport(String apiVersion, HttpServletResponse response, String yearMonth) {
        List<String> projectIdList = prepareUserDataPermission(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }
        List<SignPlanProgress> list =  signPlanProgressService.getSignPlanProgress(yearMonth,projectIdList);
        String name = "签约计划进度表-"+yearMonth.replace("-","")+"-"+ LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMddHH");

        SignPlanProgressTemplate signPlanProgressTemplate = new SignPlanProgressTemplate(name);
        signPlanProgressTemplate.appendRows(list);
        try (OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
            signPlanProgressTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("###### errorMsg: ", e);
        }

    }

    /**
     * 查询用户的权限项目
     * @param userName
     * @return
     */
    private List<String> prepareUserDataPermission(String userName) {
        List<String> projectIds = Collections.synchronizedList(new ArrayList<>());
        List<ProjectByStagesDto> dataPermissionList = idmUserService.queryUserDataPermissions(userName);
        if (CollectionUtils.isNotEmpty(dataPermissionList)) {
            for (ProjectByStagesDto dto : dataPermissionList) {
                if (dto.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
                    projectIds.add(dto.getOrgdepid());
                }
            }
        }
        return projectIds;
    }

    /**
     * 保存系统日志
     */
    private boolean saveLog(LogEventEnum logEventEnum, String module, String title, String content) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(logEventEnum);
        bo.setSource(LogSrcEnum.PC);
        bo.setModule(module);
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ONE.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        return sysLogService.add(bo,Constants.SYS);
    }
}
